package com.qianxunclub.mysql.autoconfigure;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * @author chihiro.zhang
 */
@Configuration
@EnableConfigurationProperties({DruidDataSourceProperties.class,DataSourceProperties.class})
@ConditionalOnProperty(prefix = "mybatisplus.generic", name = "enabled", havingValue = "true")
public class DatasourceConfiguration {

    @Autowired
    private DataSourceProperties dataSourceProperties;
    @Autowired
    private DruidDataSourceProperties druidDataSourceProperties;

    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(dataSourceProperties.determineDriverClassName());
        dataSource.setUrl(dataSourceProperties.determineUrl());
        dataSource.setUsername(dataSourceProperties.determineUsername());
        dataSource.setPassword(dataSourceProperties.determinePassword());
        String connectionProperties = druidDataSourceProperties.getConnectionProperties();
        String[] connectionPropertie = connectionProperties.split(";");
        Properties properties = new Properties();
        for(String connectionPrope : connectionPropertie){
            properties.setProperty(connectionPrope.split("=")[0],connectionPrope.split("=")[1]);
        }
        dataSource.setConnectProperties(properties);
        DatabaseDriver databaseDriver = DatabaseDriver.fromJdbcUrl(dataSourceProperties.determineUrl());
        String validationQuery = databaseDriver.getValidationQuery();
        if (validationQuery != null) {
            dataSource.setTestOnBorrow(true);
            dataSource.setValidationQuery(validationQuery);
        }
        return dataSource;
    }
}
